// newsmanager.cpp
#include "newsmanager.h"
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QDebug>

NewsManager::NewsManager(QObject *parent)
    : QObject(parent)
    , m_networkManager(new QNetworkAccessManager(this))
    , m_loading(false)
{
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &NewsManager::onNetworkReply);
}

void NewsManager::fetchNews()
{
    setLoading(true);
    setErrorMessage("");
    
    // 使用HTTP协议（Qt for HarmonyOS 不支持HTTPS）
    QUrl url("http://v3.alapi.cn/api/zaobao");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
    // 设置超时（10秒）
    request.setTransferTimeout(10000);
    
    // 构建POST参数
    QUrlQuery params;
    params.addQueryItem("token", "ycd0krwbhl5v2w6iafblj94y5vzqdj");
    params.addQueryItem("format", "json");
    
    QByteArray postData = params.toString(QUrl::FullyEncoded).toUtf8();
    
    qDebug() << "发送早报请求到:" << url.toString();
    qDebug() << "POST数据:" << postData;
    m_networkManager->post(request, postData);
}

void NewsManager::onNetworkReply(QNetworkReply *reply)
{
    setLoading(false);
    
    if (reply->error() != QNetworkReply::NoError) {
        qWarning() << "网络错误:" << reply->errorString();
        setErrorMessage("网络请求失败: " + reply->errorString());
        reply->deleteLater();
        return;
    }
    
    QByteArray responseData = reply->readAll();
    qDebug() << "收到响应数据，大小:" << responseData.size();
    
    parseJsonResponse(responseData);
    
    reply->deleteLater();
}

void NewsManager::parseJsonResponse(const QByteArray &data)
{
    qDebug() << "收到的原始数据:" << data;
    
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "JSON解析错误:" << parseError.errorString();
        setErrorMessage("数据解析失败: " + parseError.errorString());
        return;
    }
    
    QJsonObject root = doc.object();
    int code = root["code"].toInt();
    qDebug() << "API返回code:" << code;
    
    if (code != 200) {
        QString msg = root["msg"].toString();
        qWarning() << "API返回错误:" << msg;
        setErrorMessage("API错误: " + msg);
        return;
    }
    
    QJsonObject dataObj = root["data"].toObject();
    
    // 更新日期
    m_date = dataObj["date"].toString();
    emit dateChanged();
    
    // 更新新闻列表
    QJsonArray newsArray = dataObj["news"].toArray();
    m_newsList.clear();
    qDebug() << "新闻数组大小:" << newsArray.size();
    for (int i = 0; i < newsArray.size(); ++i) {
        QString newsItem = newsArray[i].toString();
        m_newsList.append(newsItem);
        qDebug() << "新闻" << (i+1) << ":" << newsItem;
    }
    qDebug() << "最终新闻列表大小:" << m_newsList.size();
    emit newsListChanged();
    
    // 更新微语
    m_weiyu = dataObj["weiyu"].toString();
    emit weiyuChanged();
    
    // 更新图片
    m_image = dataObj["image"].toString();
    emit imageChanged();
    
    // 更新头图
    m_headImage = dataObj["head_image"].toString();
    emit headImageChanged();
    
    qDebug() << "早报数据更新成功! 日期:" << m_date << "新闻条数:" << m_newsList.count();
}

void NewsManager::setLoading(bool loading)
{
    if (m_loading != loading) {
        m_loading = loading;
        emit loadingChanged();
    }
}

void NewsManager::setErrorMessage(const QString &message)
{
    if (m_errorMessage != message) {
        m_errorMessage = message;
        emit errorMessageChanged();
    }
}

